import axios from 'axios'
import { createAlova } from 'alova'
import { axiosRequestAdapter } from '@alova/adapter-axios'
import ReactHook from 'alova/react'

const customAxios = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

const instance = createAlova({
  requestAdapter: axiosRequestAdapter({
    axios: customAxios,
  }),
  shareRequest: true,
  statesHook: ReactHook,
  responded: {
    // 请求成功的拦截器
    onSuccess(response) {
      if (response.status >= 400) {
        throw new Error(response.statusText)
      }
      const data = response.data
      if (data.code !== 200) {
        // 抛出错误或返回reject状态的Promise实例时，此请求将抛出错误
        throw new Error(data.message)
      }
      return data
    },
    onError(err) {
      console.log(err)
    },
  },
})

export default instance
